package com.xin.di.uav.applet.service.impl;

import com.xin.di.uav.applet.po.CartItem;
import com.xin.di.uav.applet.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;


    private String getCartKey(String userId) {
        return "cart:" + userId;
    }

    @Override
    public void addItem(String userId, String productId, int quantity) {
        BoundHashOperations cartOps =
                redisTemplate.boundHashOps(getCartKey(userId));

        CartItem item = (CartItem) cartOps.get(productId);
        if (item != null) {
            item.setQuantity(item.getQuantity() + quantity);
        } else {
            item = new CartItem(productId, quantity);
        }
        cartOps.put(productId, item);
    }

    @Override
    public void removeItem(String userId, String productId) {

    }

    @Override
    public Map getCart(String userId) {
        return redisTemplate.opsForHash()
                .entries(getCartKey(userId));
    }

    @Override
    public void mergeCart(String tempUserId, String loggedInUserId) {

    }
}
